package channel_providor

import (
	"errors"
	"fmt"
	dlt645_v2007_master_connector "go-iot-gateway/internal/channel/connector/dlt645/v2007"
	iec104_master_connector "go-iot-gateway/internal/channel/connector/iec104/master"
	modbus_master_connector "go-iot-gateway/internal/channel/connector/modbus/master"
	mqtt_thingsboard_connector "go-iot-gateway/internal/channel/connector/mqtt/thingsboard"
	syschannel_connector "go-iot-gateway/internal/channel/connector/syschannel"
	channel_define "go-iot-gateway/internal/channel/define"
	"go-iot-gateway/internal/conf_table"
	"strings"
)

// 通道工厂， 根据配置创建不同的通道
func NewChannel(chl_id string) (channel_define.ConnectChannel, error) {

	channelConfig, err := conf_table.FindAllChannelByChlId(chl_id)
	if err != nil {
		return nil, err
	}

	if !channelConfig.IsValid() {
		return nil, errors.New("通道未启用")
	}

	protocolConfInfos := conf_table.ProtocolList(chl_id)

	switch strings.TrimSpace(channelConfig.Chl_protocol) {

	case channel_define.SYS_CHANNEL, "":
		connectChannel, err := syschannel_connector.NewSysChannel(*channelConfig)
		if err != nil {
			return nil, err
		}
		return connectChannel, nil
	case channel_define.MODBUS_TCP_MASTER, channel_define.MODBUS_RTU_MASTER:
		//case channel_define.MODBUS_RTU:
		connectChannel, err := modbus_master_connector.NewModbusMasterConnector(*channelConfig, protocolConfInfos)
		if err != nil {
			return nil, err
		}
		return connectChannel, nil

	case channel_define.THINGSBOARD_MQTT_CLIENT:
		connectChannel, err := mqtt_thingsboard_connector.NewThingsBoardMqttClientConnector(*channelConfig, protocolConfInfos)
		if err != nil {
			return nil, err
		}
		return connectChannel, nil

	case channel_define.IEC_104_MASTER:
		connectChannel, err := iec104_master_connector.NewIec104MasterConnector(*channelConfig, protocolConfInfos)
		if err != nil {
			return nil, err
		}
		return connectChannel, nil

	case channel_define.DLT645_2007_MASTER:
		connector, err := dlt645_v2007_master_connector.NewDlt6452007MasterConnector(*channelConfig, protocolConfInfos)
		if err != nil {
			return nil, err
		}
		return connector, nil
	}

	return nil, errors.New(fmt.Sprintf("通道类型不支持 %s %s", channelConfig.Chl_name, channelConfig.Chl_protocol))
}
